/* -----------------------------------------------------------------------------
 * PROJECT    : lwf_web
 * FILE       : WelcomeAction.java
 *
 * HISTORY:
 * Date          Author                        Description
 * ----------------------------------------------------------------------------- 
 * May 18, 2012  MyCodeTalks			       Created
 */

package net.lwf.web.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lwf.web.struts.action.form.LoginActionForm;
import net.lwf.entity.WebUser;
import net.lwf.service.UserService;
import net.lwf.util.web.WebUtil;
import net.lwf.web.constant.IWebConstant;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

public class WelcomeAction extends DispatchAction {
	
	public ActionForward display(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		WebUser webuser = (WebUser) WebUtil.getAttribute(request, IWebConstant.WEB_USER);
		
		if(webuser == null ) {
			Object pl_object = WebUtil.getAttribute(request, "IS_PRIMARY_LOGIN");
			if(pl_object != null && pl_object.toString().equalsIgnoreCase("true")) {
				return mapping.findForward("welcome-display");
			}
			else {
				return mapping.findForward("primarylogin");
			}
		}
		
		return mapping.findForward("home");
	}

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginActionForm lform = (LoginActionForm) form;
		if(lform != null) {
			String userid = lform.getUserid();
			String password = lform.getPassword();
			UserService uservice = new UserService();
			if(uservice.isPrimaryUser(userid, password)) {
				WebUtil.setAttribute(request, "IS_PRIMARY_LOGIN", "true");
				return mapping.findForward("welcome");
			}
			else {
				ActionMessages messages = new ActionMessages();
				messages.add("globalmessage", new ActionMessage("invalid.user"));
				saveErrors(request, messages);
			}
		}

		
		return mapping.findForward("primarylogin");
	}
	
}
